#include<gflags/gflags.h>
#include<brpc/server.h>
#include<butil/logging.h>
#include<thread>
#include"main.pb.h"
#include"../../Common/etcd.hpp"
#include"../../Common/channel.hpp"

DEFINE_bool(log_mod,false,"true为发布模式,false为调试模式");
DEFINE_string(log_file,"","发布模式下日志存储的文件");
DEFINE_int32(log_level,0,"要输出的日志等级");
class EchoServiceImpl:public example::EchoService
{
public:
    void Echo(google::protobuf::RpcController* controller,
                       const ::example::EchoRequest* request,
                       ::example::EchoResponse* response,
                       ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);//和RAII思想类似，在局部域结束后自动调用done->Run();
        std::cout<<"收到消息:"<<request->message()<<std::endl;
        std::string res = "我收到了你的:"+request->message()+"消息,并可以给你回复";
        response->set_message(res);
    }//EchoServiceImpl服务的一个接口，作用是对收到的信息进行回复
};
//创建服务器 添加echo服务 启动服务器 将服务注册到etcd中管理
int main(int argc,char* argv[])
{
    google::ParseCommandLineFlags(&argc,&argv,true);
    zzy_mims::init_logger(FLAGS_log_mod,FLAGS_log_file,(spdlog::level::level_enum)FLAGS_log_level);
    
     //关闭brpc的默认日志输出
    logging::LoggingSettings logset;
    logset.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(logset);

    const std::string etcd_host = "http://127.0.0.1:2379";//客户端注册中心地址
    const std::string basedir = "/service";//查询的根目录
    const std::string instance_name = "/echo/instance";//一个实例名称
    const std::string instance_host ="127.0.0.1:8082";//这个实例的服务外部访问地址
    const int listen_port = 8082;


     //1.构造服务器对象
    brpc::Server server;
    //2.向服务器新增服务
    EchoServiceImpl echo_service;
    int ret = server.AddService(&echo_service,brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if(ret == -1)
    {
        std::cout<<"添加RPC服务失败\n";
        return -1;
    }
    //3.启动服务器
        brpc::ServerOptions options;
        options.idle_timeout_sec = -1;//配置连接空闲超时时间，超时后连接被关闭
        options.num_threads = 1;//io线程数量，默认是CPU核数
    ret = server.Start(listen_port,&options);
    if(ret==-1)
    {
        std::cout<<"服务器启动失败!\n";
        return -1;
    }
    std::shared_ptr<zzy_mims::Registery> registery = std::make_shared<zzy_mims::Registery>(etcd_host);
    registery->Register(basedir+instance_name+"1",instance_host);
    server.RunUntilAskedToQuit();
}